package com.dem.android.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

import com.dem.android.R;
import com.dem.android.util.Config;
import com.dem.android.util.ImageUtil;
import com.dem.android.util.ToastUtil;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class DetailDemRuActivity extends GAActivity {

	private String finalUrl;
	public static final String APP_ID = "172351736206263";
	private Facebook mFacebook;
	private ProgressDialog progress;
	private WebView webview;
	private static String[] PERMISSIONS = new String[] { "offline_access", "read_stream", "publish_stream" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_dem_ru_activity);

		webview = (WebView) findViewById(R.id.webview);
		webview.getSettings().setJavaScriptEnabled(true);
		webview.getSettings().setBuiltInZoomControls(true);
		webview.setInitialScale(100);

		finalUrl = getIntent().getStringExtra(Config.DEM_RU_DETAIL);
//		progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
		webview.loadUrl(finalUrl);

	}

	public void save(View view) {
		new SaveToGalleryTask().execute("Dem.jpg", finalUrl);
	}

	public void share(View view) {
		new ShareTask().execute("Dem.jpg", finalUrl);
	}

	public void facebook(View view) {
		mFacebook = new Facebook(APP_ID);
		authorizeAndLike(DetailDemRuActivity.this);
	}

	@Override
	protected void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);
		mFacebook.authorizeCallback(reqCode, resultCode, data);
	}

	private void authorizeAndLike(Activity activity) {
		mFacebook.authorize(activity, PERMISSIONS, new DialogListener() {
			@Override
			public void onComplete(Bundle values) {
				Log.v("TAG", "onComplete");
				new LikePostedMessage().execute();
			}

			@Override
			public void onFacebookError(FacebookError error) {
				Log.v("TAG", "onFacebookError");
				error.printStackTrace();
			}

			@Override
			public void onError(DialogError e) {
				Log.v("TAG", "onError");
			}

			@Override
			public void onCancel() {
				Log.v("TAG", "onCancel");
			}

		});
	}

	private class SaveToGalleryTask extends AsyncTask<String, Integer, String> {
		protected String doInBackground(String... urls) {
			return ImageUtil.downloadFromUrl(DetailDemRuActivity.this, urls[0], urls[1]);
		}

		@Override
		protected void onPreExecute() {
			progress = ProgressDialog.show(DetailDemRuActivity.this, getApplicationContext().getString(R.string.loading),
					getApplicationContext().getString(R.string.please_wait), true, false);
			super.onPreExecute();
		}

		protected void onPostExecute(String result) {
			if (null != progress)
				progress.dismiss();
			// save to gallary
			ContentValues values = new ContentValues();
			values.put(Images.Media.MIME_TYPE, "image/jpeg");
			Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
			OutputStream outstream;
			try {
				outstream = getContentResolver().openOutputStream(uri);
				BitmapFactory.decodeFile(result).compress(Bitmap.CompressFormat.JPEG, 100, outstream);
				outstream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			ToastUtil.showText(DetailDemRuActivity.this, getString(R.string.image_svaed));

		}
	}

	private class ShareTask extends AsyncTask<String, Integer, String> {
		protected String doInBackground(String... urls) {
			return ImageUtil.downloadFromUrl(DetailDemRuActivity.this, urls[0], urls[1]);
		}

		@Override
		protected void onPreExecute() {
			progress = ProgressDialog.show(DetailDemRuActivity.this, getApplicationContext().getString(R.string.loading),
					getApplicationContext().getString(R.string.please_wait), true, false);
			super.onPreExecute();
		}

		protected void onPostExecute(String result) {
			if (null != progress)
				progress.dismiss();

			// save to gallary
			ContentValues values = new ContentValues();
			values.put(Images.Media.MIME_TYPE, "image/jpeg");
			Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
			OutputStream outstream;
			try {
				outstream = getContentResolver().openOutputStream(uri);
				BitmapFactory.decodeFile(result).compress(Bitmap.CompressFormat.JPEG, 100, outstream);
				outstream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
			shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getText(R.string.app_name));
			shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
			shareIntent.setType("image/png");
			startActivity(Intent.createChooser(shareIntent, getText(R.string.choose_service)));

		}
	}

	private class LikePostedMessage extends AsyncTask<Void, Void, Integer> {
		@Override
		protected Integer doInBackground(Void... params) {
			String response = "";
			Integer code = 0;
			try {
				Bundle bundle = new Bundle();
				bundle.putString("message", getString(R.string.app_name));
				bundle.putString("picture", finalUrl);
				bundle.putString("name", getString(R.string.app_name));
				bundle.putString("link", finalUrl);
				bundle.putString("caption", "https://market.android.com/details?id=com.dem.android");

				response = mFacebook.request("me/feed", bundle, "POST");
				Log.v("FaceBook_Response", response);
				try {
					JSONObject json = new JSONObject(response);
					if (!json.isNull("id")) {
						String id = json.getString("id");
						response = mFacebook.request(id + "/likes", new Bundle(), "POST");
						if (response.equalsIgnoreCase("true")) {
							code = 1;
						}
					}
				} catch (JSONException e) {
					code = 0;
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
				code = 0;
			} catch (IOException e) {
				e.printStackTrace();
				code = 0;
			}
			return code;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result == 1) {
				Toast.makeText(getApplicationContext(), "Facebook Like success!", Toast.LENGTH_LONG).show();
			} else if (result == 0) {
				Toast.makeText(getApplicationContext(), "Facebook Like did fail!", Toast.LENGTH_LONG).show();
			}
			super.onPostExecute(result);
		}
	}

}
